import React from 'react';
import { connect } from 'dva'
import queryString from 'query-string'
import {
  Button,
  Card,
  Modal,
  Tabs,
  Spin,
  Alert,
  Switch,
  Popover,
  message
} from 'antd'
import List from "./commodityBankList";
import PageHeaderLayout from 'components/Layout/PageHeaderLayout';
import OrderFilterUnExpand from 'components/Filter/NormalFilter';
import GeneralFilter from 'components/Filter/GeneralFilter'
import LwjTable from 'components/LwjTable/LwjTable'
import styles from './commodityBankIndex.less'
import { Loader } from 'components'

const commodityBanks=({location,dispatch,commodityBank,app,loading})=>{
  location.query = queryString.parse(location.search);
  const { items, currentItem, pagination, modifyVisible,deleteVisible,isExpand, optionType,selectRows, selectedRowKeys, currentType, store} = commodityBank;
  const TabPane = Tabs.TabPane;
  const confirm = Modal.confirm;
  const breadcrumbList = [
    {
      title: '商品管理',

    }, {
      title: '商品库',

    }
  ];

  const setCurrentItem =(record)=>{
    dispatch({
      type: 'commodityBank/setCurrentItem',
      payload: record
    })
  }
  const onModify=(record)=>{
    setCurrentItem(record)
    dispatch({
      type: 'commodityBank/setModifyVisible',
      payload: true
    })
  }
  const onDelete = (record) => {
    confirm({
      global,
      title: '您确认要删除该商品库?',
      content: '该商品库删除后，将会影响商品',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'commodityBank/dele',
          payload:{
            storeId:record.id,

          }
        })
      },
      onCancel() { }
    })
  }

  const update = (record) => {
    dispatch({
      type: 'commodityBank/toggleModal',
      flag: true,
      id: record.id
    });
    dispatch({
      type: 'commodityBank/productList',
      payload: {
        start: 0,
        limit: 10
      }
    })
  }

  const listProps = {
    dataSource: items,
    loading: loading.global,
    pagination,
    pageChangeAction: 'commodityBank/query',
    dispatch,
    currentItem,
    global: loading.global,
    onModify: onModify,
    onDelete:onDelete,
    modifyVisible,
    deleteVisible,
    location,
    update
  };
  const filterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'name',
        title: '商品库名称'
      },
    ],
    onFilterChange(value) {
      dispatch({
        type: 'commodityBank/query',
        payload: {
          ...value
        }
      })
    },
    isExpand,
    noExpand() {
      dispatch({ type: 'commodityBank/unExpandFilter', payload: {} })
    },
    expand() {
      dispatch({ type: 'commodityBank/expandFilter', payload: {} })
    }
  }
  // 表格属性
  const productTableProps = {
    dataSource: store.list,
    loading: loading.effects['commodityBank/productList'],
    pagination: store.pagination,
    pageChangeAction: 'commodityBank/productList',
    dispatch,
    location,
    rowSelection:{
      onChange: (selectedRowKeys, selectedRows) => {
        dispatch({
          type: 'commodityBank/setSelectedRows',
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows
        })
      },
      getCheckboxProps: record => ({
        disabled: !record.has_material, // Column configuration not to be checked
        name: record.id.toString(),
      }),
      selectedRowKeys: store.selectedRowKeys
    },
    locale:{
      emptyText:"暂无数据"
    }
  };

  const productsColumns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%'
    }, {
      title: '商品图片',
      dataIndex: 'goods_info',
      key: 'goods_info',
      width: '15%',
      render: (text, record) => {
        return (
          <Popover content={<img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productBigImg} />} title="商品图片" placement="right">
            <img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productSmallImg} />
          </Popover>
        )
      }
    }, {
      title: '商品分类',
      dataIndex: 'cate_name',
      key: 'cate_name',
      width: '10%'
    }, {
      title: 'SPU',
      dataIndex: 'goods_id',
      key: 'goods_id',
      width: '10%'
    }, {
      title: 'SKU',
      dataIndex: 'sku_id',
      key: 'sku_id',
      width: '10%'
    }, {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: '8%'
    },
    {
      title: '建议零售价',
      dataIndex: 'price',
      key: 'price',
      width: '7%',
      render : (text) => text && text.toFixed(2)
    },{
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      render: (text, record) => {
        return (
          <span>{record.isLinked ? '已关联' : '未关联'}</span>
        )
      }
    }, {
      title: '关联',
      key: 'handle',
      width: '10%',
      render: (text, record) => {
        if (record.has_material) {
          return (<Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => onChangeProduct(value, [record])} checked={record.isLinked} />)
        } else {
          return (<span>商品未绑定物料</span>)
        }
      }
    }
  ]
  // 弹窗数据
  const productFilterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'name',
        title: '商品名称'
      },
      {
        type: 'input',
        id: 'goods_id',
        title: 'SPU编码'
      }, {
        type: 'input',
        id: 'id',
        title: 'SKU编码'
      }
    ],
    Col: 6,
    onFilterChange(value) {
      dispatch({
        type: 'commodityBank/changeParam',
        queryParam: value
      })
      dispatch({
        type: 'commodityBank/productList',
        payload: {
          start: 0,
          limit: store.pagination.defaultPageSize
        }
      })
    }
  }

  const onChangeProduct = (value, record, flag) => {
    if (record && record.length == 0) {
      message.error("请选择" + (value ? '关联' : '取消关联') + "商品项");
      return;
    }
    let _temp = record.filter((item) => item.isLinked != value).map((item) => item.id);
    if (_temp && _temp.length > 0) {
      dispatch({
        type: 'commodityBank/link',
        param: {
          commodityIds: _temp,
          storeId: store.id,
          linkedStatus: (value ? 'LINK' : 'CANCEL')
        },
        flag
      })
    } else {
      message.error("选择的商品项已" + (value ? '关联' : '取消关联'));
    }
  }

  const toggleModal = (flag) => {
    dispatch({
      type: 'commodityBank/toggleModal',
      flag: flag
    })
  }

  return (
    <PageHeaderLayout title="商品库" breadcrumbList={breadcrumbList}>
      <Card bordered={false}>

          <OrderFilterUnExpand {...filterProps} />

          <List effects={loading.effects} {...listProps} />

          <Modal
            visible={store.modalVisible}
            title="商品池"
            onOk={() => toggleModal(false)}
            onCancel={() => toggleModal(false)}
            width={950}
            destroyOnClose={true}
            footer={[
              <Button key="back" onClick={() => toggleModal(false)}>关闭</Button>,
            ]}>
            <GeneralFilter {...productFilterProps} />
            <div className={styles.productFilterBtnGap}>
              <Button type="primary" onClick={() => onChangeProduct(true, store.selectedRows, 'multiple')}>批量关联</Button>
              <Button type="primary" onClick={() => onChangeProduct(false, store.selectedRows, 'multiple')}>批量取关</Button>
            </div>
            <LwjTable {...productTableProps} columns={productsColumns} />
            <Loader spinning={loading.effects['commodityBank/link','commodityBank/alllink']} />
          </Modal>

      </Card>
    </PageHeaderLayout>
  )
};
export default connect(({ commodityBank, app, loading ,load}) => ({ commodityBank, app, loading,load }))(commodityBanks)
